/**
 * Copyright (c) 2016-2019  All rights reserved.
 * <p>
 * https://www.yuncheng.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.yuncheng.modules.sys.controller;

import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.config.SystemLevelConfig;
import io.yuncheng.common.exception.RRException;
import io.yuncheng.common.utils.Constant;
import io.yuncheng.common.utils.PageUtils;
import io.yuncheng.common.utils.R;
import io.yuncheng.modules.sys.entity.SysDeptEntity;
import io.yuncheng.modules.sys.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 部门管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/dept")
@Api(tags = "部门管理")
public class SysDeptController extends AbstractController {
    @Autowired
    private SysDeptService sysDeptService;
    @Resource
    private SystemLevelConfig.SystemLevel systemLevel;
    @Resource
    private DictConfig dictConfig;

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation("列表")
    public List<SysDeptEntity> list() {
        List<SysDeptEntity> deptList = queryListConfirm(new HashMap<String, Object>());

        return deptList;
    }

    /**
     * 列表
     */
    @GetMapping("/list-no-app")
    @ApiOperation("排除应用列表")
    public List<SysDeptEntity> appList(String name) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("name", name);
        List<SysDeptEntity> deptList = queryListConfirm(stringObjectHashMap);

        List<SysDeptEntity> collect = deptList.stream().filter(a -> !a.getType().equals(Constant.DeptTypeEnum.APP.getValue())).collect(Collectors.toList());
        return collect;
    }
    /**
     * 列表
     */
    @GetMapping("/list-app")
    @ApiOperation("全部应用列表")
    public List<SysDeptEntity> appListAll(String name) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>(4);
        stringObjectHashMap.put("name", name);
        List<SysDeptEntity> deptList = queryListConfirm(stringObjectHashMap);
        return deptList;
    }

    /**
     * 列表
     */
    @GetMapping("/list-level-one")
    @ApiOperation("查询一级机构")
    public List<SysDeptEntity> oneLevelList(String name) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("name", name);
        List<SysDeptEntity> deptList = queryListConfirm(stringObjectHashMap);
        // 省 以及一级机构
        // 市区以及市区一级机构
        List<SysDeptEntity> collect = deptList.stream().filter(a -> a.getType() == systemLevel.getSysLevelEnum().getValue() || a.getType() == Constant.DeptTypeEnum.DEPT_1.getValue()).collect(Collectors.toList());
        return collect;
    }

    /**
     * 保存
     */
    @RequestMapping("/level-two-save")
    public R levelTwoSave(@RequestBody SysDeptEntity sysDept) {

        SysDeptEntity byId = sysDeptService.getById(sysDept.getParentId());
        if (byId == null || !byId.getType().equals(Constant.DeptTypeEnum.DEPT_1.getValue())) {
            throw new RRException("请选定正确的机构");
        }
        sysDeptService.checkDept(sysDept.getParentId(),"的数据");
        //状态
        sysDept.setStatus(Constant.StatusType.NORMAL.getValue());
        //类型
        sysDept.setType(Constant.DeptTypeEnum.DEPT_2.getValue());
        sysDeptService.save(sysDept);

        return R.ok();
    }
    /**
     * 保存
     */
    @RequestMapping("/level-one-save")
    public R levelOneSave(@RequestBody SysDeptEntity sysDept) {

        SysDeptEntity byId = sysDeptService.getById(sysDept.getParentId());
        if (byId == null) {
            throw new RRException("请选定正确的机构");
        }
        //状态
        sysDept.setStatus(Constant.StatusType.NORMAL.getValue());
        //类型
        sysDept.setType(Constant.DeptTypeEnum.DEPT_1.getValue());
        sysDeptService.save(sysDept);

        return R.ok();
    }

    /**
     * 选择部门(添加、修改菜单)
     */
    @ApiOperation("选择部门")
    @GetMapping("/select")
    public R select() {
        List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());

        //添加一级部门
        if (getUserId() == Constant.SUPER_ADMIN) {
            SysDeptEntity root = new SysDeptEntity();
            root.setDeptId(0L);
            root.setName("一级部门");
            root.setParentId(-1L);
            root.setOpen(true);
            deptList.add(root);
        }

        return R.ok().put("deptList", deptList);
    }

    /**
     * 注销
     */
    @PostMapping("/write-off")
    @ApiOperation("注销")
    public R updateOff(Long id) {
        SysDeptEntity byId = sysDeptService.getById(id);
        if (byId == null) {
            throw new RRException("无对应id");
        }
       sysDeptService.checkEntity(byId,"的数据");
        byId.setStatus(Constant.StatusType.OFF.getValue());
        List<SysDeptEntity> deptList = sysDeptService.queryDeptList(id);
        if (deptList.size() > 0) {
            for (SysDeptEntity deptEntity : deptList) {
                if (deptEntity.getStatus().equals(Constant.StatusType.NORMAL.getValue())) {
                    return R.error("请先注销该机构下的应用系统和用户！");
                }

            }
        }
        sysDeptService.updateById(byId);
        return R.ok();
    }

    /**
     * 注销
     */
    @PostMapping("/write-on")
    @ApiOperation("启用")
    public R updateOn(Long id) {
        SysDeptEntity byId = sysDeptService.getById(id);
        if (byId == null) {
            throw new RRException("无对应id");
        }
        //省级
        sysDeptService.checkEntity(byId,"的数据");
        byId.setStatus(Constant.StatusType.NORMAL.getValue());
        sysDeptService.updateById(byId);
        return R.ok();
    }

    /**
     * 上级部门Id(管理员则为0)
     */
    @GetMapping("/info")
    @ApiOperation("上级部门Id")
    public R info() {
        long deptId = 0;
        if (getUserId() != Constant.SUPER_ADMIN) {
            List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());
            Long parentId = null;
            for (SysDeptEntity sysDeptEntity : deptList) {
                if (parentId == null) {
                    parentId = sysDeptEntity.getParentId();
                    continue;
                }

                if (parentId > sysDeptEntity.getParentId().longValue()) {
                    parentId = sysDeptEntity.getParentId();
                }
            }
            deptId = parentId;
        }

        return R.ok().put("deptId", deptId);
    }

    /**
     * 信息
     */
    @ApiOperation("信息")
    @GetMapping("/info/{deptId}")
    public R info(@PathVariable("deptId") Long deptId) {
        SysDeptEntity dept = sysDeptService.getById(deptId);

        return R.ok().put("dept", dept);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("保存")
    public R save(@RequestBody SysDeptEntity dept) {
        sysDeptService.save(dept);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("修改")
    public R update(@RequestBody SysDeptEntity dept) {
        sysDeptService.updateById(dept);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation("删除")
    public R delete(long deptId) {
        //判断是否有子部门
        List<Long> deptList = sysDeptService.queryDetpIdList(deptId);
        if (deptList.size() > 0) {
            return R.error("请先删除子机构和机构的应用");
        }

        sysDeptService.removeById(deptId);

        return R.ok();
    }

    /**
     *
     * @param params
     * @return
     */
    public List<SysDeptEntity> queryListConfirm(Map<String, Object> params) {
        List<SysDeptEntity> deptList = sysDeptService.queryList(params);
        List<SysDeptEntity> confirm = deptList.stream().filter(a -> a.getStatus().equals(Constant.StatusType.NORMAL.getValue())).collect(Collectors.toList());
        Collections.sort(confirm,(a,b)-> (int) (a.getDeptId() - b.getDeptId()));
        return confirm ;
    }

    /**
     * 列表
     */
    @PostMapping("/list-page")
    @ApiOperation("列表分页")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = sysDeptService.queryPageConfirm(params);
        return R.ok().put("page",page);
    }
    /**
     * 列表
     */
    @PostMapping("/list-page-level-two")
    @ApiOperation("列表分页")
    public R listType(@RequestParam Map<String, Object> params) {
        params.put("type",Constant.DeptTypeEnum.DEPT_2.getValue());
        PageUtils page = sysDeptService.queryPageConfirm(params);
        return R.ok().put("page",page);
    }

}
